package com.outdd.vaietool.module.story.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.outdd.vaietool.common.BaseResponse;
import com.outdd.vaietool.common.annotation.AopLog;
import com.outdd.vaietool.common.constants.UrlMapping;
import com.outdd.vaietool.common.utils.BaseUtil;
import com.outdd.vaietool.common.utils.BrowserUtil;
import com.outdd.vaietool.common.utils.ReptileUtil;
import com.outdd.vaietool.common.utils.convert.EncodingConvert;
import com.outdd.vaietool.common.utils.email.EmailUtil;
import com.outdd.vaietool.common.utils.io.IoConvertUtil;
import com.outdd.vaietool.common.utils.io.IoUtil;
import com.outdd.vaietool.module.story.dao.entity.StoryEntity;
import com.outdd.vaietool.module.story.service.StoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.List;

/**
 * @program: StoryController
 * @description:
 * @author: VAIE
 * @create: 2021-05-13 11:45
 **/
@RestController
@RequestMapping(UrlMapping.STORY)
@Slf4j
public class StoryController {

    @Autowired
    StoryService storyService;

    @AopLog("匹配搜索")
    @GetMapping("/matchingSearch")
    public BaseResponse matchingSearch(String keyword) {
        String vallue = EncodingConvert.zhConvertUrl(keyword);
        Document documentOfHttps = ReptileUtil.getDocumentOfHttps("https://www.qidian.com/ajax/Search/AutoComplete?2SwfYLCicAXRQfYgNhnHCE1WmCUAt2Mf1wroLpgU&siteid=1&query="+vallue);
        String text = documentOfHttps.text();
        JSONObject jsonObject = JSONObject.parseObject(text);
        JSONArray suggestions = jsonObject.getJSONArray("suggestions");
        return BaseResponse.success(suggestions);
    }

    @AopLog("搜索")
    @GetMapping("/queryStory")
    public BaseResponse<List<StoryEntity>> queryStory(String keyword) {
        List<StoryEntity> storyEntities = storyService.queryStory(keyword);
        return BaseResponse.success(storyEntities);
    }


    @AopLog("爬取小说")
    @GetMapping("/captureStory")
    public void captureStory(String url, String source, String title,String uuid, HttpServletResponse response) {
        String de = storyService.captureStory(url,source,uuid);

        Boolean z = EmailUtil.sendEmail("vaielx@163.com", "有人下载了小说", "有人下载了小说：" + title);

        log.info("发送邮件",z);
        File xians = IoUtil.write(de, BaseUtil.getUUID());
        if (ObjectUtils.isNotEmpty(xians)) {
            InputStream inputStream = IoConvertUtil.fileConvertInputStream(xians);
            BrowserUtil.download(inputStream, title, ".txt", response);
        }

    }

}
